﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;


namespace CashOrCard.Extensions
{
    public class CashOrCardAuthorizeExtension: AuthorizeAttribute
    {
        public string AllowPermissions { get; set; }
        public string ErrorView { get; set; }
        public string _loginView = "_TimeoutError";
        public string LoginView
        {
            get
            {
                return _loginView;
            }
            set
            {
                _loginView = value;
            }
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string[] userPermissionsArr = System.Web.Security.Roles.GetRolesForUser();
            bool isAuthorized = false;
            if (httpContext.Request.IsAuthenticated)
            {
                foreach (string permission in AllowPermissions.Split(','))
                {
                    if (userPermissionsArr.Contains(permission))
                    {
                        isAuthorized = true;
                        break;
                    }
                }
            }            
            return isAuthorized;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {            
            base.HandleUnauthorizedRequest(filterContext);
            if (HttpContext.Current.Request.IsAuthenticated)
            {
                filterContext.Result = new PartialViewResult { ViewName = ErrorView };
            }
            else
            {
                filterContext.Result = new PartialViewResult { ViewName = LoginView };
            }
        }
    }
}